import { vpost, sonpost, fpost, gpost, vlink } from '@api/axios'

let systemTime

// 获取当前系统时间
function getSustemTime(goods, timer) {
    vpost(vlink.currentTime).then(re => {
        systemTime = re
        getCurrentTime(goods, timer)
    })
}
// 循环获得当前系统时间
function getCurrentTime(goods, timer) {
    goods.forEach(item => {
        doCountDown(item, timer)
    })
}
// 判读是1小时倒计时还是24小时倒计时
function doCountDown(item, timer) {
    let h_24 = 24 * 60 * 60 * 1000 // 获得24小时毫秒
    let h_1 = 60 * 60 * 1000 // 获得1小时毫秒
    if (item.count_down_type === 0) {
        countDown(h_24, item, timer)
    } else if (item.count_down_type === 1) {
        countDown(h_1, item, timer)
    } else {
        return
    }
}
// 倒计时
function countDown(hr, item, timer) {
    let star = new Date(item.count_down).getTime()
    let countDown = hr - (systemTime - star)
    if (countDown <= 0) {
        item['countDown'] = {
            h: '00',
            m: '00',
            s: '00',
        }
        clearInterval(timer)
    } else {
        let leave1 = countDown % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
        let hours = Math.floor(leave1 / (3600 * 1000))//计算出小时数
        let leave2 = leave1 % (3600 * 1000)    //计算小时数后剩余的毫秒数
        let minutes = Math.floor(leave2 / (60 * 1000))//计算相差分钟数
        let leave3 = leave2 % (60 * 1000)      //计算分钟数后剩余的毫秒数
        let seconds = Math.round(leave3 / 1000)  //计算相差毫秒
        item['countDown'] = {
            h: padLeftZero(hours),
            m: padLeftZero(minutes),
            s: padLeftZero(seconds),
        }
    }
}

function padLeftZero(str) {
    str = '00' + str
    return str.substr(str.length - 2, 2);
}

export { systemTime, getSustemTime, getCurrentTime, doCountDown, countDown }